package com.xlhj.yucloud.web.service;

import com.xlhj.yucloud.entity.SysUserInfo;
import com.xlhj.yucloud.service.SysMenuInfoService;
import com.xlhj.yucloud.service.SysRoleInfoService;
import com.xlhj.yucloud.service.SysUserInfoService;
import com.xlhj.yucloud.web.model.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @author: liucaijing
 * @description: UserDetailsServiceImpl
 * @date: 2021/9/10 10:51
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private SysUserInfoService userInfoService;
    @Autowired
    private SysMenuInfoService menuInfoService;
    @Autowired
    private SysRoleInfoService roleInfoService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if (ObjectUtils.isEmpty(username)) {
            throw new RuntimeException("用户名不能为空!");
        }
        //查询用户信息
        SysUserInfo userInfo = userInfoService.findUserByUserName(username);
        if (ObjectUtils.isEmpty(userInfo)) {
            throw new RuntimeException("用户不存在!");
        }
        List<SimpleGrantedAuthority> authorities = getUserAuthorities(userInfo.getId());
        return new LoginUser(userInfo.getId(), userInfo.getUserName(), userInfo.getPassword(), authorities);
    }

    /**
     * 根据用户ID查询菜单和角色权限
     * @param userId
     * @return
     */
    public List<SimpleGrantedAuthority> getUserAuthorities(Long userId) {
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        //获取用户菜单权限
        Set<String> menuPerms = menuInfoService.getMenuPermsByUserId(userId);
        if (menuPerms.size() > 0) {
            for (String perm : menuPerms) {
                if (StringUtils.hasLength(perm)) {
                    SimpleGrantedAuthority authority = new SimpleGrantedAuthority(perm);
                    authorities.add(authority);
                }
            }
        }
        //获取用户角色权限
        Set<String> rolePerms = roleInfoService.getRolePermsByUserId(userId);
        if (rolePerms.size() > 0) {
            for (String perm : rolePerms) {
                SimpleGrantedAuthority authority = new SimpleGrantedAuthority("ROLE_" + perm);
                authorities.add(authority);
            }
        }
        return authorities;
    }
}
